package leetcode.editor.cn;

import java.util.Stack;

/**
 * @Description 有效的括号
 * @Author wxl
 * @Date 2025/7/16 13:58
 */
public class IsValid {
    public static void main(String[] args) {
        IsValid isValid = new IsValid();
        String s = "{()}]";
        System.out.println(isValid.isValid(s));
    }

    public boolean isValid(String s) {
        Stack<Character> stack= new Stack<>();
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '(' || chars[i] == '[' || chars[i] == '{') {
                stack.push(chars[i]);
            }  else {
                if (!stack.isEmpty() && stack.peek() == leftOfChar(chars[i])) {
                    stack.pop();
                }else  {
                    // 不匹配的情况
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public char leftOfChar(char c) {
        if (c == ')') {
            return '(';
        }
        if (c == ']') {
            return '[';
        }
        return '{';
    }
}
